package com.bang.controller;

import com.bang.dao.DepartmentDao;
import com.bang.dao.EmployeeDao;
import com.bang.pojo.Department;
import com.bang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees=employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/add")
    public String toAdd(Model model){
        Collection<Department> departments=departmentDao.getDepartment();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/add")
    public String AddEmployee(Employee employee,Model model){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/update/{id}")
    public String toUpdate(@PathVariable("id")Integer id,Model model){

        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments=departmentDao.getDepartment();
        model.addAttribute("departments",departments);

        return "emp/update";
    }

    @PostMapping("/update")
    public String updateEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

}
